package com.jdh.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName: public class WebsocketMsgAffirmListener {
 * @Author: jdh
 * @CreateTime: 2024-05-13  10:52
 * @Description: 正常流程的消费端对消息的监听
 * @Version: 1.0
 */
@Component
@Slf4j
public class WebsocketMsgAffirmListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    @Value("${websocket.msg.affirm.retryCount:3}")
    private Integer retryCount;

    /**
     * 对websocket消息未进行确认的进入待确认队列中进行判断是否需要重发处理
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitListener(queues = "affirm_queue")
    public void websocketMsgAffirmListener(Message message, Channel channel) throws Exception {

        MessageProperties messageProperties = message.getMessageProperties();
        String exchange = messageProperties.getReceivedExchange();
        String routingKey = messageProperties.getReceivedRoutingKey();
        String consumerQueue = messageProperties.getConsumerQueue();
        long deliveryTag = messageProperties.getDeliveryTag();
        String msg = new String(message.getBody());
        try {
            System.out.println("监听到消息：" + msg + " = " + new Date());
            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            //消息重回队列
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
